package com.ai.trickycards.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.ai.trickycards.App
import com.ai.trickycards.R
import com.ai.trickycards.databinding.ActivityPrifileBinding
import com.ai.trickycards.databinding.AdapterLevelItemBinding
import com.ai.trickycards.entity.enumeration.MedalEnum
import com.ai.trickycards.ui.adapter.BaseRecyclerAdapter
import com.ai.trickycards.ui.adapter.BaseViewHolder
import com.ai.trickycards.ui.dialog.CongratsDialog
import com.ai.trickycards.ui.fragment.CustomizeFragment
import com.ai.trickycards.ui.fragment.DataFragment
import com.ai.trickycards.utils.Utils
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue

@SuppressLint("SetTextI18n")
class ProfileActivity : FragmentActivity() {

    private val appViewModel by lazy {
        (application as App).getAppViewModel()
    }

    private val binding by lazy {
        ActivityPrifileBinding.inflate(layoutInflater)
    }

    private val tabs by lazy {
        listOf(
            binding.tvTabCustomize,
            binding.tvTabData
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        //setWindowInsets(binding.root)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        window.statusBarColor = Color.TRANSPARENT
        window.navigationBarColor = Color.TRANSPARENT

        binding.ivClose.setOnClickListener { finish() }
        binding.ivSetting.setOnClickListener { startActivity(Intent(this, SettingActivity::class.java)) }
        tabs[0].isSelected = true
        tabs.forEachIndexed { index, tab ->
            tab.setOnClickListener {
                tabs.forEach { tabItem ->
                    tabItem.isSelected = tabItem == tab
                }
                binding.viewPager.currentItem = index
            }
        }

        setupMedalAdapter()
        bindData()
        setupTab()

        binding.tvLevelClaim.setOnClickListener {
            val medalEnum = MedalEnum.entries[binding.viewPagerLevel.currentItem]
            CongratsDialog(this@ProfileActivity, appViewModel, medalEnum) {
                setMedalClaimButton(binding.viewPagerLevel.currentItem)
            }.show()
        }
    }

    private fun bindData() {
        lifecycleScope.launch {
            appViewModel.userInfoFlow.collect { userInfo ->
                binding.ivHead.setImageResource(userInfo.headIcon)
                binding.tvNick.text = userInfo.userName
                binding.tvLevel.text = "Lvl ${userInfo.level}"
                binding.progressLevel.progress = Utils.getLevelProgress(userInfo.level)

                Utils.getMedal(userInfo.level)?.let { levelMedal ->
                    binding.viewPagerLevel.currentItem = levelMedal.ordinal
                }

            }
        }
    }

    private fun setupTab() {
        binding.viewPager.isUserInputEnabled = false
        binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            val fragments = listOf(
                CustomizeFragment(),
                DataFragment()
            )

            override fun getItemCount() = fragments.size

            override fun createFragment(position: Int) = fragments[position]
        }
    }

    /**
     * 勋章适配器
     */
    private fun setupMedalAdapter() {
        val list = MedalEnum.entries
        setMedalClaimButton(0)

        binding.viewPagerLevel.offscreenPageLimit = 5
        binding.viewPagerLevel.adapter = object : BaseRecyclerAdapter(R.layout.adapter_level_item) {
            override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
                val binding = AdapterLevelItemBinding.bind(holder.itemView)
                binding.ivImg.setImageResource(list[position].icon)
                // 是否达到对应的勋章等级
                val userMedal = Utils.getMedal(appViewModel.userInfoFlow.value.level)
                val isAchieve = (userMedal?.ordinal ?: -1) >= position
                if (isAchieve) {
                    binding.ivImg.imageTintList = ColorStateList.valueOf(Color.TRANSPARENT)
                } else {
                    binding.ivImg.imageTintList = ColorStateList.valueOf(Color.parseColor("#991C1B1C"))
                }
            }

            override fun getItemCount() = list.size
        }

        binding.viewPagerLevel.setPageTransformer { page, position ->
            val absPos = position.absoluteValue
            val scale = 1 - absPos * 0.4f
            page.translationX = -position * page.width * 0.65f
            page.scaleY = scale
            page.scaleX = scale
        }

        binding.viewPagerLevel.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setMedalClaimButton(position)
            }
        })
    }

    /**
     * 设置勋章收集按钮状态
     */
    private fun setMedalClaimButton(position: Int) {
        val userInfo = appViewModel.userInfoFlow.value
        val userMedal = Utils.getMedal(userInfo.level)
        val currentMedal = MedalEnum.entries[position]
        // 是否达到对应的勋章等级
        val isAchieve = (userMedal?.ordinal ?: -1) >= position
        // 是否已经收下对应的勋章
        val isClaim = userInfo.claimMedalList.contains(currentMedal)

        // 设置按钮是否可用
        binding.tvLevelClaim.isEnabled = isAchieve && !isClaim
        // 设置按钮文案
        binding.tvLevelClaim.text = if (isClaim) "Done" else "Claim"
    }
}